package com.ruanyin.dao.impl;

import com.ruanyin.domain.User;
import com.ruanyin.utils.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class UserDaoImpl implements com.ruanyin.dao.UserDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<User> findAll() {
        // 使用JDBC操作数据库
        String sql = "select * from user";
        List<User> users = template.query(sql, new BeanPropertyRowMapper<User>(User.class));
        System.out.println("UserDao:" + users);

        return users;
    }

    @Override
    public User findUserById(int id) {
        String sql = "select * from user where id=?";
        User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id);
        System.out.println("UserDao:" + user);
        return user;
    }

    @Override
    public void alterUser(User newUser) {
        String sql = "update user set gender=?,age=?,address=?,qq=?,email=? where id=?";
        template.update(sql, newUser.getGender(), newUser.getAge(), newUser.getAddress(), newUser.getQq(), newUser.getEmail(), newUser.getId());
    }

    @Override
    public void deleteUserById(int id) {
        String sql = "delete from user where id=?";
        template.update(sql, id);
    }

    @Override
    public void addUser(User user) {
        String sql = "insert into user(name,gender,age,address,qq,email) values(?, ?, ?, ?, ?, ?)";
        template.update(sql, user.getName(), user.getGender(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail());
    }

    @Override
    public int findTotalCount() {
        String sql = "select * from user";
        return template.queryForObject(sql, Integer.class);
    }

    @Override
    public List<User> findByPage(int start, int rows) {
        String sql = "select * from user limit ? , ?";
        return template.query(sql, new BeanPropertyRowMapper<User>(User.class), start, rows);
    }
}
